﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class TaskEditNew : BasicPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            BasicPageInit();
            if (!IsPostBack)
            {
                var id = Request.QueryString["id"];

                if (!string.IsNullOrEmpty(id))
                {
                    var sql = string.Format("select * from Task where id={0}", id);
                    var dt = DbHelper.GetData(sql);
                    if (dt.Rows.Count > 0)
                    {
                        var row = dt.Rows[0];

                        this.txtId.Text = row["Id"].ToString();
                        this.txtName.Text = row["TaskName"].ToString();
                        this.txtContent.Text = row["TaskContent"].ToString();
                        this.txtRemarks.Text = row["Remarks"].ToString();
                    }
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            var id = this.txtId.Text;
            var name = this.txtName.Text;
            var content = this.txtContent.Text;
            var remarks = this.txtRemarks.Text;

            //如果id不为空，说明是修改任务；否则说明是添加or新增
            if (string.IsNullOrEmpty(id))
            {
                var userId = Session["UserId"].ToString();
                var sql = string.Format("insert into Task (TaskName,TaskContent,CreatedUserId,Remarks) values ('{0}','{1}',{2},'{3}')", name, content, userId, remarks);
                var inserted = DbHelper.ExeOperation(sql);
                if (inserted > 0)
                {
                    var success = "<script>alert('恭喜你，添加成功！')</script>";
                    Response.Write(success);
                    Response.Redirect("Default.aspx");
                }
                else
                {
                    var error = "<script>alert('很遗憾，添加失败！')</script>";
                    Response.Write(error);
                }
            }
            else
            {
                var sql = string.Format("update Task set TaskName='{0}',TaskContent='{1}',Remarks='{2}' where Id={3}", name, content, remarks, id);
                var updated = DbHelper.ExeOperation(sql);
                if (updated > 0)
                {
                    var success = "<script>alert('恭喜你，修改成功！')</script>";
                    Response.Write(success);
                    Response.Redirect("Default.aspx");
                }
                else
                {
                    var error = "<script>alert('很遗憾，修改失败！')</script>";
                    Response.Write(error);
                }
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("Default.aspx");
        }
    }
}